/**
 * Created by jerome.arnoult on 19/05/14.
 */
function gamegui(){
    this.mouseUp = true;
    this.initCellPos = {};
    this.initMousePos = {};
    this.initStagePosition = {};
    this.editMode = false;
    this.currentCursor = 'pointer';
    this.currentButton = 'selector';
    this.currentOrientation = "N";
    this.currentShapeID = "";
    this.currentGroupID = "";
    this.initGui();
}

gamegui.prototype.initGui = function(){
    /**
     * Build editor menu
     */
    //Colorpicker
    $(".colorpicker .input input").colpick({
        colorScheme:'dark',
        color: '#000000',
        flat:false,
        layout: 'hex',
        submit: 0,
        onChange: function(hsb,hex,rgb,el,bySetColor){
            $(el).val(hex).css('border-color','#'+hex);
        }
    });
    //Switch
    $(".switch-slider").toggleClick(function(){
        $(this).animate({marginLeft:'0'}, 200).trigger( "switchOn" );
        var rel = $(this).attr('rel');
        $("#"+rel).attr('checked', true);
    },function(){
        $(this).animate({marginLeft:'-50px'}, 200).trigger( "switchOff" );
        var rel = $(this).attr('rel');
        $("#"+rel).attr('checked', false);
    }).on("switchOn",function(){
        game.gameGui.execAction($(this).attr("data-action-on"));
    }).on("switchOff",function(){
        game.gameGui.execAction($(this).attr("data-action-off"));
    });
    //Menu accordion
    $( "#editorMenu .accordion-menu, #editorLayers" ).accordion({
        active: false,
        collapsible: true,
        heightStyle: "fill",
        header: "li.menuTitle"
    });
    //Range input
    $("div.range input").on('input change',function(){
        var value = $(this).val();
        var suffix = $(this).attr('data-suffix');
        var action = $(this).attr('data-action-onchange');
        $(this).parent().find('.rangeValue').html(value+suffix);
        game.gameGui.execAction(action);
    });
    //Dialog box
    $("#jqueryWindow").dialog({
        autoOpen: false
    });
    //Action button
    $("a").on('click',function(event){
        var action = $(this).attr('data-action');
        if($(this).attr('href') == "")
            event.preventDefault();
        game.gameGui.execAction(action);
    }).on('mouseover',function(){
        window.status = "";
    });
}
gamegui.prototype.addEvtUI = function(id){
    $("#shapeLayers_"+id+" a").on('click',function(event){
        var action = $(this).attr('data-action');
        if($(this).attr('href') == "")
            event.preventDefault();
        game.gameGui.execAction(action);
    }).on('mouseover',function(){
        window.status = "";
    });
    $("#shapeLayers_"+id+" .switch-slider").toggleClick(function(){
        var rel = $(this).attr('rel');
        $("#"+rel).attr('checked', true);
        $(this).animate({marginLeft:'0'}, 200).trigger( "switchOn" );
    },function(){
        var rel = $(this).attr('rel');
        $("#"+rel).attr('checked', false);
        $(this).animate({marginLeft:'-50px'}, 200).trigger( "switchOff" );
    }).on("switchOn",function(){
        game.gameGui.execAction($(this).attr("data-action-on"));
    }).on("switchOff",function(){
        game.gameGui.execAction($(this).attr("data-action-off"));
    });
}
gamegui.prototype.moveCursor = function(evt){
    if(game.gameGui.mouseUp === false){
        if(game.gameGui.editMode == true) {
            var o = evt.target;
            posx = o.getAttribute('data-posx');
            posy = o.getAttribute('data-posy');
        }
    }
}
gamegui.prototype.clickCursor = function(evt){
    evt.preventDefault();
    game.gameGui.mouseUp = true;
    switch (evt.which) {
        case 1://Left click

            break;
        case 2://Middle click

            break;
        case 3://Right click

            break;
    }
}
gamegui.prototype.startDragCursor = function(evt){
    evt.preventDefault();

}
gamegui.prototype.cancelBuild = function(evt){
    evt.preventDefault();

}
gamegui.prototype.rotateConstruct = function(evt){
    evt.preventDefault();
    switch (game.gameGui.currentOrientation) {
        case "N":
            game.gameGui.currentOrientation = "E";
            break;
        case "E":
            game.gameGui.currentOrientation = "S";
            break;
        case "S":
            game.gameGui.currentOrientation = "W";
            break;
        case "W":
            game.gameGui.currentOrientation = "N";
            break;
    }
}
gamegui.prototype.execAction = function(action){
    var action = action.split(":");
    console.log(action);
    switch(action[0]){
        case "editor":
            switch(action[1]){
                case "NewCollection":
                    var html = $("#newCollection").html();
                    $("#jqueryWindow").dialog("option","modal",true)
                        .dialog("option","title","New Collection")
                        .html(html);
                    $("#jqueryWindow").dialog("open");
                    $("#jqueryWindow #newcollection_ok").on("click",function(e){
                        e.preventDefault();
                        var name = $("#jqueryWindow #newcollection_name").val();
                        var html = $("#htmlPathern #collection").html();
                        html = html.replace('%name%',name);
                        $("#editorLayers #projectLayers").html(html);
                        $("#jqueryWindow").dialog("close");
                        game.gameEditor.newCollection(name);
                    });
                    break;

                case "NewShape":
                    var html = $("#newShape").html();
                    $("#jqueryWindow").dialog("option","modal",true)
                        .dialog("option","title","New Shape")
                        .html(html);
                    $("#jqueryWindow").dialog("open");
                    $("#jqueryWindow #newshape_ok").on("click",function(e){
                        e.preventDefault();
                        var name = $("#jqueryWindow #newshape_name").val();
                        var size =  $("#jqueryWindow #newshape_format").val();
                        var html = $("#htmlPathern #shape").html();

                        //If no collection, create it
                        if($("#editorLayers #shapes").length == 0){
                            var preHtml = $("#htmlPathern #shapeNoCollection").html();
                            $("#editorLayers #projectLayers").html(preHtml);
                            game.gameEditor.newCollection("New unamed project");
                        }

                        //Create shape and get Token
                        var id = game.gameEditor.addShape(name, size);
                        html = html.replace('%name%',name);
                        html = html.replace(/%id%/g,id);

                        //Add HTML
                        $("#editorLayers #shapes").append(html);

                        //add UI
                        if(!!$("#editorLayers #shapes").data("ui-accordion"))
                            $("#editorLayers #shapes").accordion('destroy');
                        $("#editorLayers #shapes").accordion({
                            active: false,
                            heightStyle: "fill",
                            collapsible: true,
                            header: ".shapeTitle"
                        });
                        $( "#editorLayers #shapes .shapeLayers" ).tabs();

                        //Close modal
                        $("#jqueryWindow").dialog("close");
                        //reload events
                        game.gameGui.addEvtUI(id);
                    });
                    break;
                case "OpenSave":
                    var html = $("#openSave").html();
                    $("#jqueryWindow").dialog("option","modal",true)
                        .dialog("option","title","Open Save")
                        .html(html);
                    $("#jqueryWindow").dialog("open");
                    $("#jqueryWindow #opensave_ok").on("click",function(e){
                        e.preventDefault();
                        $.ajax("./saves/"+$("#opensave_file").val()).success(function(data){
                            var json;
                            try {
                                json = JSON.parse(data);
                            } catch (e) {
                                alert('Fichier Json incorrect')
                            }
                            if(json != undefined) {
                                game.gameEditor.openSave(json);
                            }
                        })
                    });
                    break;
                case "Undo":
                    break;
                case "Redo":
                    break;
                case "Save":
                    break;
                case "Export":
                    break;
                case "ActiveGrid":
                    game.gameMap.displayGrid();
                    break;
                case "DeactiveGrid":
                    game.gameMap.hideGrid();
                    break;
                case "UpdateGrid":
                    game.gameMap.updateGrid();
                    break;
                case "OpenShape":
                    game.gameGui.parseShape(action[2]);
                    break;
                case "getNorth":
                    game.gameEditor.cleanShape();
                    game.gameGui.currentOrientation = "N";
                    game.gameGui.currentShapeID = action[2];
                    var size = game.gameEditor.collection.shapes[action[2]].format;
                    game.gameMap.createInitTiles(size);
                    game.gameEditor.parseShape(action[2]);
                    break;
                case "getEast":
                    game.gameEditor.cleanShape();
                    game.gameGui.currentOrientation = "E";
                    game.gameGui.currentShapeID = action[2];
                    var size = game.gameEditor.collection.shapes[action[2]].format;
                    game.gameMap.createInitTiles(size);
                    game.gameEditor.parseShape(action[2]);
                    break;
                case "getSouth":
                    game.gameEditor.cleanShape();
                    game.gameGui.currentOrientation = "S";
                    game.gameGui.currentShapeID = action[2];
                    var size = game.gameEditor.collection.shapes[action[2]].format;
                    game.gameMap.createInitTiles(size);
                    game.gameEditor.parseShape(action[2]);
                    break;
                case "getWest":
                    game.gameEditor.cleanShape();
                    game.gameGui.currentOrientation = "W";
                    game.gameGui.currentShapeID = action[2];
                    var size = game.gameEditor.collection.shapes[action[2]].format;
                    game.gameMap.createInitTiles(size);
                    game.gameEditor.parseShape(action[2]);
                    break;
                case "Selector":
                    game.gameGui.changeCursor("selector");
                    game.gameGui.activeButton("selector");
                    break;
                case "PointsSelector":
                    game.gameGui.changeCursor("pointsSelector");
                    game.gameGui.activeButton("pointsSelector");
                    break;
                case "NewGroup":
                    game.gameGui.changeCursor("pointer");
                    game.gameGui.activeButton("newGroup");
                    break;
                case "Spot":
                    game.gameGui.changeCursor("pointer");
                    game.gameGui.activeButton("spot");
                    break;
                case "Line":
                    game.gameGui.changeCursor("pointer");
                    game.gameGui.activeButton("line");
                    break;
                case "Circle":
                    game.gameGui.changeCursor("pointer");
                    game.gameGui.activeButton("circle");
                    break;
                case "Rect":
                    game.gameGui.changeCursor("pointer");
                    game.gameGui.activeButton("rectangle");
                    break;
                case "Polygon":
                    game.gameGui.changeCursor("pointer");
                    game.gameGui.activeButton("polygon");
                    break;
                case "Arc":
                    game.gameGui.changeCursor("pointer");
                    game.gameGui.activeButton("arc");
                    break;
                case "Ellipse":
                    game.gameGui.changeCursor("pointer");
                    game.gameGui.activeButton("ellipse");
                    break;
                case "BezierCurv":
                    game.gameGui.changeCursor("pointer");
                    game.gameGui.activeButton("bezier");
                    break;
            }
            break;
        case "shape":

            break;
        case "group":
            switch(action[1]){
                case "EditPoints":
                    game.gameGui.currentGroupID = action[2];
                    $(".group_points").hide();
                    $(".group_properties").removeClass("on");
                    $("#group_"+ action[2] +"_instructions").show().parent().find(".group_properties").addClass("on");
                    game.gameEditor.displayEditPoints(action[2]);
                    break;
                case "EditStrokeColor":

                    break;
                case "EditFillColor":

                    break;
            }
            break;
    }
}
gamegui.prototype.changeCursor = function(name){
    $(body).removeClass(game.gameGui.currentCursor).addClass(name);
    game.gameGui.currentCursor = name;
}
gamegui.prototype.activeButton = function(name){
    $("a."+game.gameGui.currentButton).removeClass("on").addClass("off");
    $("a."+name).removeClass("off").addClass("on");
    game.gameGui.currentButton = name;
}
